<script setup lang="ts">
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { onLoad, onReady, onShow } from '@dcloudio/uni-app'
import { ref, reactive, onMounted, toRaw } from 'vue'
import { useI18n } from 'vue-i18n'
import { uploadImage } from '@/api/login'
import { RSA_encryption, rsaEncryptSet, RSA_encryption1, md5Str } from '@/utils/index'
import Rsa from '@/utils/rsa_s.js'
import VConsole from 'vconsole'

const { t, locale } = useI18n()
const timeNumber = ref(60)
const isGetCode = ref(false)
const showLanguage = ref(false) // 弹出语言窗
const memberStore = useMemberStore()
const popup = ref() // 弹窗ref
const currentLanguage = ref<any>({})
const paramsData = reactive({data: {}}) // 路径参数
const hideShooting = ref<boolean>(false); // 显示按钮

const videoRef = ref<any>(null);

const srcUrl = ref('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4')

const photoBase64 = ref('')
// 视频地址
const videoSrc = ref<any>("");

const myCanvas = ref<any>(null);

const isVideoReady = ref(false); // 可选，用于控制何时开始绘制帧。


const drawImage = ref();

const ctx = ref(null);

const cameraInput = ref<any>();
const languageList = reactive({
  // zh_CN,en_US,th_TH,vi_VN
  list: [
    {
      type: 'zh_CN',
      name: t('loginIndex.Chinese'),
      id: '1',
      icon: '../../static/image/china-icon.png',
    },
    {
      type: 'en_US',
      name: t('loginIndex.English'),
      id: '2',
      icon: '../../static/image/english-icon.png',
    },
    // {
    //   type: 'French',
    //   name: t('loginIndex.French'),
    //   id: '3',
    //   icon: '../../static/image/french-icon.png',
    // }
  ],
}) // 语言列表
// const vConsole = new VConsole()
onLoad((options) => {
  console.log(' - - - >  load', options)
  if (options.mobile) {
    paramsData.data = options
  }
  // videoSrc.value = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4';
  // videoRef.value.play();
})
onReady(() => {
  var context = uni.createCanvasContext('myCanvas')
   ctx.value = context;
  //  console.log(' - - - >  onReady', context, ' - - : 6 6 6', ctx.value)
})
onShow(() => {
  // console.log(' - - - >  show')
  var queryString = window.location.search;
  queryString = queryString.substring(1);
  var params = queryString.split('&');
  var queryParams:any = {};
  params.forEach((param) => {
      var parts = param.split('=');
      queryParams[parts[0]] = parts[1];
  });
  paramsData.data = queryParams; 
  console.log(' - - > 9 9 9', navigator, navigator.mediaDevices, queryParams);
})

onMounted(() => {
  let lang = memberStore.language
  if (lang) {
    currentLanguage.value = toRaw(languageList.list).find((item) => item.type === lang)
  }
  // const canvasIns = uni.createCanvasContext('myCanvas', this)
  // ctx.value = canvasIns;
  // console.log(' - - - >  mounted 11', canvasIns);

   // #ifdef H5 || WEB
  
  // #endif

  // const query = uni.createSelectorQuery().in(this);
  // query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {
  //   const canvas = res[0].node;
  //   ctx.value = canvas.getContext('2d');
  //   console.log(' - - - >  mounted 22', canvas, ctx.value);
  // });
})
// 打开前置摄像头
const openForent = () => {
  console.log(' - - > camera : ', 333);
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true  })
    .then(stream => {
      // 将摄像头捕捉到的视频流绑定到video元素上
       console.log(' - - > camera 1: ', stream);
       if (videoRef.value) {
        // 创建一个Blob URL
        videoSrc.value = stream;
          // video.value.srcObject = stream;
          // video.value.play();
          console.log(' - - > camera 1.1: ',videoSrc.value, stream);
          // video.value.play();
        }
      console.log(' - - > camera 2: ', videoRef.value, stream);
    })
    .catch(error => {
      console.error("摄像头访问失败:", error);
      // uni.showToast({
      //   title: "请检查是否已打开摄像头权限",
      //   icon: "none",
      //   duration: 3000
      // })
      // uni.showModal({
      //   title: "提示",
      //   content: "请检查是否已打开摄像头权限",
      //   showCancel: false
      // });
    });
  } else {
    console.log('当前浏览器不支持getUserMedia方法！');
     uni.showToast({
        title: "当前浏览器不支持获取用户媒体！",
        icon: "none",
        duration: 3000
      })
    // uni.showModal({
    //     title: "提示",
    //     content: "当前浏览器不支持",
    //     showCancel: false
    //   });
  }
   
}
const loginSuccess = (profile: LoginResult) => {
  // 保存用户信息
  memberStore.setProfile(profile)
  // 成功提示
  // uni.showToast({ icon: 'success', title: '登录成功' })
  setTimeout(() => {
    // 页面跳转
    uni.switchTab({ url: '/pages/index/index' })
    //uni.navigateBack()
  }, 100)
}
// 下一步
const nextCb = () => {
}

// 选择语言
const selectLan = () => {
  popup.value.open('bottom')
}
const changePopup = (e) => {
  console.log('当前模式：' + e.type + ',状态：' + e.show)
}
const closePopup = () => {
  popup.value.close()
}
// 选择语言
const changeLanguage = (item) => {
  currentLanguage.value = item
  memberStore.setLanguage(item.type)
  // uni.setStorageSync('language', item.type)
  // i18n.locale = item.type
  uni.$emit('i18nChange')
  popup.value.close()
  // #ifdef H5
  window.location.reload()
  // #endif
  // #ifdef MP-WEIXIN || APP-PLUS
  // uni.reLaunch({ url: '/pages/login/loginPass' })
  // #endif
}
const getBse64Url = () => {
  uni.chooseImage({
  count: 1, // 默认9
  sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
  sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
  success: function (res) {
    const tempFilePaths = res.tempFilePaths;
    console.log(' - - - > tempFilePaths', tempFilePaths);
    uploadImage(tempFilePaths[0]); // 上传图片或进行其他操作
  }
});
 
}
// 开始拍摄
const startCamera = () => { 
  // 在页面的 JS 文件中
  uni.chooseImage({
    count: 1, // 默认拍照数量
    sourceType: ['camera'], // 只能从相机选择
    camera: 'front', // 使用前置摄像头
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      console.log(tempFilePaths[0]); // 输出图片的本地文件路径列表
      // 这里可以将图片路径显示在页面上或上传到服务器
    },
    fail: (err) => {
      console.error(err);
    }
  });
}
// 摄像头
const handleCamera = (event:any) => {
  // 获取文件列表
  const files = event.target.files;
  if (files.length > 0) {
    // 获取第一张图片
    const imageFile = files[0];
    // 可以将图片转换为base64或者上传到服务器等操作
    const reader = new FileReader();
    reader.readAsDataURL(imageFile);
    reader.onload = (e) => {
      const base64Image = e.target.result;
      console.log(base64Image); // 输出图片的base64编码
      // 这里可以进行后续处理，如显示图片、上传等
    };
  }
}
const triggerCamera = () => {
  // 触发相机
  const cameraInp = cameraInput.value;
  cameraInp.click();
}
// 拍照片
const takePhoto = () => {
  // const context = ctx.value.getContext('2d');
  // if (ctx.value && isVideoReady.value && videoRef.value) {

  // }
  // if(process.env.VUE_APP_PLATFORM === 'h5') {
    // const ctx = myCanvas.value.getContext('2d')
    // console.log(' 绘制 - - > ',ctx)
    // ctx.drawImage(videoRef.value, 0, 0);
    
    // #ifdef H5 || WEB
      const video = videoRef.value.$el;
      const canvas = myCanvas.value.$el;
      console.log(' 绘制 - - #> ',video, canvas)
      var ctx = uni.createCanvasContext('myCanvas')
      var vodeoCtx = uni.createVideoContext('myVideo')
      // const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, 200, 200);
      ctx.drawImage(videoRef.value, 0, 0, 200, 200);
      // ctx.draw();
      console.log(' 绘制 - - 2 > ',ctx, video, videoRef.value, canvas.width, canvas.height)

      // 转换为Base64并下载
      // const dataURL = canvas.toDataURL('image/png');
      //  console.log(' 绘制 - - *> ', dataURL)
      // #endif
    
      // }
  
    // ctx.setFillStyle('red');
    // ctx.fillRect(10, 10, 150, 75);
    // ctx.draw(); 

    // ctx.drawImage('', 0, 0);


  // #ifdef H5 || APP-PLUS
  const canvas1 = myCanvas.value?.$el;
  var ctx1 = uni.createCanvasContext('myCanvas');

  console.log("图片数据URL : - - - > 1 ", canvas1, ctx1);

  // uni.chooseImage({
  //   success: function(res){
  //     ctx1.drawImage(res.tempFilePaths[0], 0, 0, 150, 100)
  //     ctx1.draw()
  //   }
  // })
  // #endif


  // ctx.value.draw() 
  console.log("图片数据URL : - - - >  ", isVideoReady.value, videoRef.value, '|', ctx);
  // const imageDataURL = ctx.value.canvas.toDataURL('image/png');
  // console.log("图片数据URL : - - - > 1 ", ctx.value.canvas, imageDataURL);
  //  photoBase64.value = imageDataURL;
  // 这里可以处理图片数据，例如显示或者上传等
  // putbaseData(imageDataURL);

  // setTimeout(() => {
    saveAsBase64();
  // }, 2000);
}
const takePhoto1 = () => { 
  const ctx = uni.createCanvasContext('myCanvas', this);
  ctx.setFillStyle('red');
  ctx.fillRect(10, 10, 150, 75); // 绘制一个红色的矩形
  ctx.draw();
 
  // 将Canvas内容转换为base64格式
  uni.canvasToTempFilePath({
    canvasId: 'myCanvas',
    success: (res) => {
      console.log('临时路径', res.tempFilePath); // 可以在这里查看生成的临时文件路径（可选）
      // 直接使用toDataURL也可以，但uni-app中通常使用canvasToTempFilePath转换后再转为base64，因为toDataURL在某些情况下可能不支持直接在uni-app中使用
      // 这里演示如何从临时路径获取base64，实际应用中可以直接使用toDataURL的结果
      uni.getFileSystemManager().readFile({
        filePath: res.tempFilePath, // 替换为实际的文件路径或直接使用toDataURL的结果
        encoding: 'base64',
        success: (readRes) => {
          console.log('临时路径', res.tempFilePath); 
          photoBase64.value = `data:image/png;base64,${readRes.data}`; // 注意这里的写法可能有误，应为`readRes.data`而非`readReadRes.data`，这里仅为示例说明如何处理
        }
      });
    }
  });
}
const saveAsBase64 = () => {
  uni.canvasToTempFilePath({
    canvasId: 'myCanvas',
    success: (res) => {
      // 获取临时文件路径
      const tempFilePath = res.tempFilePath
      console.log('tempFilePath:', res, tempFilePath)
      photoBase64.value = tempFilePath;
      
      // if (tempFilePath) {
      //   const reader = new FileReader();
      //   reader.onload = (e) => {
      //     const base64Image = e.target.result;
      //     console.log(base64Image); // 这里你将得到Base64编码的字符串
      //     // 你可以在这里做进一步处理，比如存储到data属性中
      //     photoBase64.value = base64Image;
      //   };
      //   reader.readAsDataURL(tempFilePath); // 读取文件并转换为Base64编码
      // }
      
      // uni.getFileSystemManager().readFile({
      //   filePath: tempFilePath,
      //   encoding: 'base64',
      //   success: (res) => {
      //     photoBase64.value = 'data:image/png;base64,' + res.data
      //     console.log('Base64数据11:', photoBase64.value)
      //     // 这里可以处理base64数据，如上传或显示
      //   }
      // })
    },
    fail: (err) => {
      console.error('Base64数据00 err:', err);
    }
  })
}
// 获取
const putbaseData = (image:string) => {
  let params = {
    mobile: paramsData.data.mobile || '',
    order: paramsData.data.order || '',
    image: image || ''
  }
  uploadImage(params).then(res => {
    if (res && res.code === 200) {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      });
    }
  }).catch(err => {
    console.log('err :', err)
    uni.showToast({
      title: err.msg,
      icon: 'none'
    });
  })
}
const startShooting = () => { 
    hideShooting.value = true;
    openForent();
}
const clearVideo = () => {    
  // 关闭摄像头    
   const stream = videoSrc.value.getTracks().forEach(track => {   
     track.stop();  
   });     
    videoSrc.value = null;
}  
const handleVideoReady = () => {
  isVideoReady.value = true; // 设置视频已准备好标志。
}
// 初始化页面节点
const initCanvas = () => {
  console.log(" loadedmetadata - - > 初始化页面节点 ");
  const video = videoRef.value.$el;
  const canvas = myCanvas.value.$el;
  console.log(" loadedmetadata - - > 初始化页面节点 ok", video, canvas);
  // 设置canvas与video同尺寸
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  // 处理跨域问题
  video.crossOrigin = 'anonymous';
  isVideoReady.value = true; // 设置视频已准备好标志。
};

</script>
<template>
  <view class="" style="width: 100vw;height: 100vh;background-color: #fff;">
      <view
        class="wrap-content"
        style="width: 100vw;height: 100vh;background-color: transparent;opacity: 1;position: absolute;top: 0; left: 0;z-index: 1;"
      >
      <!-- <button @click="triggerCamera">拍照</button> -->
      <!-- <input type="file" accept="image/*" capture="camera" style="display: none;" @change="handleCamera" :ref="cameraInput"> -->
      <!-- <input type="file" accept="image/*" capture="camera" @change="handleCamera"> -->
      <!-- <view class="start-btn" @click="startCamera">Start shooting</view> -->
      <view class="video-wrap-cont flexC">
        <view v-if="!hideShooting" class="start-btn" @click="startShooting">
          Start shooting
        </view>
        <video 
          ref="videoRef"
          object-fit="fill" 
          :show-center-play-btn="false" 
          :srcObject="videoSrc" 
          muted
          playsinline
          class="video-wrap" 
          @loadedmetadata="initCanvas"
          :autoplay="true" 
          :controls="false"></video>
        <button class="take-photo-btn" @click="takePhoto">{{t('camera.photograph')}}</button>
        <!-- style="display:none" -->
        <!-- <canvas 
          type="2d" 
          id="myCanvas" 
          class="canvas" 
          canvas-id="myCanvas" 
          ref="myCanvas" 
          ></canvas> -->
          <!-- #ifdef MP-WEIXIN -->
          <canvas 
            type="2d" 
            id="myCanvas"
            class="canvas" 
            canvas-id="myCanvas"
            style="width:300px;height:300px"
          ></canvas>
          <!-- #endif -->

          <!-- #ifdef H5 || APP-PLUS -->
          <canvas 
            ref="myCanvas"
            
            class="canvas" 
            style="width:200px;height:200px"
          ></canvas>
          <image class="user-icon" ref="drawImage"  src="/static/image/icon-02.png" /> 
          <!-- #endif -->
         <image class="user-icon" v-if="photoBase64" :src="photoBase64" /> 
      </view>  
      </view>
  </view>
</template>
<style lang="scss">
page {
  height: 100%;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
  background: #ffffff;
  background: red;
}
.wrap-content {
  padding-top: 45%;
}
.video-wrap {
  width: 228rpx;
  height: 228rpx;
  border-radius: 120rpx;
}
.user-icon {
  width: 228rpx;
  height: 228rpx;
  border: 1rpx solid #ccc;
}
.canvas {
  border: 1rpx solid #aaa;
  width: 228rpx;
  height: 228rpx;
}
.btn_verification {
  display: inline-flex;
  padding: 30rpx;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
  width: 40%;
  height: 104rpx;
  line-height: 104rpx;
  border-radius: 20rpx;
  text-align: center;
  background: #1773ff;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}
.time-num {
  font-size: 32rpx;
  font-weight: 600;
  color: #999999;
}
.form-bet {
  justify-content: space-between;
}
.image_bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 0;
}
.login_txt_wrap {
  position: relative;
  z-index: 2;
  margin-top: 250rpx;
}
.login_txt {
  color: #0a2f4d;
  font-family: 'Alibaba PuHuiTi 3.0';
  font-size: 70rpx;
  font-weight: bolder;
  height: 98rpx;
  line-height: 98rpx;
}
.login_subtxt {
  color: #0a2f4d40;
  height: 42rpx;
  line-height: 42rpx;
  font-family: 'PingFang SC';
  font-size: 30rpx;
  font-style: normal;
  font-weight: 400;
  letter-spacing: 0.3rpx;
}
.select_lan {
  margin-bottom: 50rpx;
  justify-content: flex-start;
}
.image_lan {
  width: 28rpx;
  height: 28rpx;
  margin-left: 5rpx;
}
.login {
  display: flex;
  flex-direction: column;
  margin-top: 80rpx;
  padding: 10rpx 20rpx 20rpx;
  .input_wrap {
    width: 100%;
    height: 104rpx;
    line-height: 104rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    border: 1px solid #ddd;
    padding-left: 30rpx;
    margin-bottom: 10rpx;
    border-radius: 20rpx;
    border: 2rpx solid #eaeaea;
    background: #f0f5f9;
  }

  .next-wrap {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 90rpx;
  }
  .next-btn {
    width: 650rpx;
    height: 110rpx;
    border-radius: 20rpx;
    background: #1773ff;
    text-align: center;
    box-shadow: 0 18px 48px 0 #0000001a, 0 22px 48px 0 #00000014;
    color: #ffffff;
    font-family: 'PingFang SC';
    font-size: 32rpx;
    font-style: normal;
    font-weight: 600;
    line-height: 110rpx;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;

    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #019aff;
  }
  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;

    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;

      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;

      button {
        padding: 0;
        background-color: transparent;

        &::after {
          border: none;
        }
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }

    .icon-weixin::before {
      border-color: #019aff;
      color: #019aff;
    }
  }
  .input_wrap_ {
    width: 55%;
    margin-bottom: 0;
  }
}
.form-item-image {
  .uni-forms-item__content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    .image-code {
      width: 55%;
      display: inline-block;
    }

    .code-img-wrapper {
      display: inline-block;
    }
  }
}
@keyframes animate__shakeY {
  0% {
    transform: translate(0, 0);
  }

  50% {
    transform: translate(0, -5rpx);
  }

  100% {
    transform: translate(0, 0);
  }
}
.animate__shakeY {
  animation: animate__shakeY 0.2s ease-in-out 3;
}
.popup-content {
  border-top-left-radius: 10rpx;
  border-top-right-radius: 10rpx;
}
.popup-content-head {
  height: 124rpx;
  position: relative;
  border-bottom: 2rpx solid #eaeaea;
}
.head-txt {
  color: #07133b;
  text-align: center;
  font-family: 'PingFang SC';
  font-size: 34rpx;
  font-style: normal;
  font-weight: 500;
}
.image_close_ {
  position: absolute;
  top: 36rpx;
  right: 30rpx;
  width: 48rpx;
  height: 48rpx;
}
.button-privacy-wrap {
  position: relative;

  .button-opacity {
    opacity: 0;
    position: absolute;
    z-index: 1;
  }
}
.image_coun {
  width: 48rpx;
  height: 48rpx;
  margin-right: 20rpx;
}
.list-wrap {
  padding-bottom: 200rpx;
}
.item-lef-txt {
  color: #0a2f4d;
  font-family: 'PingFang SC';
  font-size: 32rpx;
  font-weight: 400;
}
.language-item {
  width: calc(100% - 40rpx);
  height: 120rpx;
  margin-left: 40rpx;
  padding-right: 40rpx;
  border-bottom: 2rpx solid #eaeaea;
  justify-content: space-between;
}
.image_coun_select {
  width: 40rpx;
  height: 40rpx;
  margin-right: 0rpx;
}
.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;

  .radio {
    transform: scale(0.6);
    margin-right: -4rpx;
    margin-top: -4rpx;
    vertical-align: middle;
  }

  .link {
    display: inline;
    color: #019aff;
  }
}
.start-btn {
  color: #fff;
  font-size: 32rpx;
  background: blue;
  padding: 6rpx 20rpx;
  border-radius: 8rpx;
  
}
.take-photo-btn {
  margin-top: 200rpx;  
  background-color: blue;
  color: #ffffff;
  padding: 4rpx 20rpx;
  font-size: 32rpx;
  border-radius: 8rpx;

}
</style>
